// packageD/ActivityDetail/ActivityDetail.js
var app = getApp();
const DrainageScene = require('../../utils/drainage_scene.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    store_id: "", // 门店拓客
    //领取人数大于4
    lingquBox: true,
    // 购买人数大于4
    newGmBox: true,
    // 活动介绍内容是否全部展示
    boxShow: true,
    // 背景图片
    bosPto: true,
    audio_link: "",
    songStop: true,
    infoList: {},

    poster_open:0,
    poster_show:false,
    poster_url:'',

    show:false,
    imgPath: app.globalData.imgPath,

    style: 0,//浏览记录样式
    browseLoadMore: true,
    browsePage: 1,
    browseData: [],
    currentSwperIndex: 0,

    groupPage: 1,
    groupData: [],
    groupLoadMore: true,
    showGroupPop: false,
    timer:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      kind: options.id,
      store_id: options.store_id,
    });
    if(options.share_tag){
      this.data.share_uid = options.mid;
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split("&");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          console.log("59", chil_arr);
          if (chil_arr[0] == "id") {
            this.setData({
              kind: chil_arr[1],
            });
          } else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
            this.data.share_uid = chil_arr[1];
          }
        }
      }
    }
  },
  tapLoadWatch(e){
    let img = e.currentTarget.dataset.img
    wx.previewImage({
        current: img, // 当前显示图片的http链接
        urls: [img] // 需要预览的图片http链接列表
      })
  },
  setPosterShow(){
    this.setData({poster_show:!this.data.poster_show});
  },
  getPosterImage(){
    if(this.data.poster_url!='') {
      this.setData({poster_show:true});
      return;
    }
    let urlStr = app.getNetAddresss(
      "plugin.share-activity.frontend.activity.get-poster"
    );
    app._getNetWork({
      data: {
        activity_id: this.data.kind,
      },
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            poster_show:true,
            poster_url:res.data.poster
          });
        }
      }
    });
  },
  toGoods(extinfo = {}) {
    let isBindDrainageScene = DrainageScene.bindDrainageScene({
      scene: 9,
      title: this.data.infoList.name
    });
    if(!isBindDrainageScene) return;//爆客码绑定场景

    if (Date.parse(new Date()) / 1000 < this.data.infoList.star_time) {
      wx.showToast({
        title: "还没到开始时间",
        icon: "none",
        duration: 1500,
      });
      return;
    }
    if (Date.parse(new Date()) / 1000 > this.data.infoList.end_time) {
      wx.showToast({
        title: "活动已结束",
        icon: "none",
        duration: 1500,
      });
      return;
    }
    let diyfrom = this.data.infoList.diyform_id;
    let url = "";
    if (diyfrom) {
      url = "/packageC/diyform/diyform?scene=" + diyfrom;
    } else {
      url = '/packageD/buy/myOrder_v2/myOrder_v2?tag=-2';
    }
    url = url + 
        "&goodsId=" +
        this.data.infoList.goods_id +
        "&optionsId=" +
        this.data.infoList.option_id +
        "&total=" +
        this.data.infoList.total;
    if (this.data.store_id) {
      url = url + "&store_id=" + this.data.store_id;
    }
    if (this.data.infoList.group_id) {
      url = url + '&activityType=GroupGoods';
      url = url + '&id=' + this.data.infoList.group_id;
    }

    if(this.data.infoList.group_id) {
      url = `/packageA/detail_v2/detail_v2?id=${this.data.infoList.group_id}/${this.data.infoList.store_id}&name=group`;
    }
    if(extinfo.activityType == 'GroupDetail') {
      url = "/packageB/member/group/GroupDetail/GroupDetail?id=" + this.groupDetailID + "&store_id=" + this.data.infoList.store_id;
    }

    url = url + '&activity_id=' + this.data.kind;
    if(this.data.share_uid) url = url + '&share_uid=' + this.data.share_uid;//分享者奖励需要
    wx.navigateTo({
      url: url,
    });
  },
  countdown() {
    let that = this;
    let now = new Date();
    let nowseon = String(Date.parse(now)).substr(0, 10);
    let end = that.data.infoList.end_time;
    if (end - nowseon <= 0) {
      console.log(end, nowseon);
      that.setData({
        stop: false,
      });
      return;
    }
    var msec = end - nowseon;
    let day = parseInt(msec / 60 / 60 / 24),
      hr = parseInt((msec / 60 / 60) % 24),
      min = parseInt((msec / 60) % 60),
      sec = parseInt(msec % 60);
    hr = hr > 9 ? hr : "0" + hr;
    min = min > 9 ? min : "0" + min;
    sec = sec > 9 ? sec : "0" + sec;
    that.setData({
      Day: day,
      Hour: hr,
      Min: min,
      Sec: sec,
    });
    // 一秒后递归
    this.data.timer = setTimeout(() => {
      this.countdown();
    }, 1000);
  },
  handleContact(e) {
    console.log(e.detail.path);
    console.log(e.detail.query);
  },
  linkTomember() {
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
  },
  linkToorder() {
    if(this.data.infoList.open_group_list === 1) {
      return wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=0&orderType=groups",
      });
    }
    wx.navigateTo({
      url: "/packageA/member/myOrder_v2/myOrder_v2?status=0",
    });
  },
  setDataByTabIndex() {
    this.setData({
      first_content: this.data.infoList.agreement,
    });
    let article = this.data.first_content;

  },
  replaceDetail(details) {
    var texts = ""; //待拼接的内容
    while (details.indexOf("<img") != -1) {
      //寻找img 循环
      texts += details.substring("0", details.indexOf("<img") + 4); //截取到<img前面的内容
      details = details.substring(details.indexOf("<img") + 4); //<img 后面的内容
      if (
        details.indexOf("style=") != -1 &&
        details.indexOf("style=") < details.indexOf(">")
      ) {
        texts +=
          details.substring(0, details.indexOf('style="') + 7) +
          "max-width:100%;height:auto;margin:0 auto;"; //从 <img 后面的内容 截取到style= 加上自己要加的内容
        details = details.substring(details.indexOf('style="') + 7); //style后面的内容拼接
      } else {
        texts += ' style="max-width:100%;height:auto;margin:0 auto;" ';
      }
    }
    texts += details; //最后拼接的内容
    return texts;
  },
  tapOn() {
    this.setData({
      boxShow: !this.data.boxShow,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if(this.audioCtx) this.audioCtx.pause();
    if(this.data.timer){
      this.data.timer = null;
      clearTimeout(this.data.timer)
    } 
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(this.audioCtx) this.audioCtx.destroy();
    if(this.data.timer){
      this.data.timer = null;
      clearTimeout(this.data.timer)
    } 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    let that = this;
    let value = wx.getStorageSync("yz_uid");
    let mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.share_title,
      query: "id=" + that.data.kind + "&mid=" + mid + "&share_tag=2",
    };
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let value = wx.getStorageSync("yz_uid");
    let mid = 0;
    if (value) {
      mid = value;
    }
    return {
      title: this.data.share_title,
      path: "/packageD/ActivityDetail/ActivityDetail?id=" + this.data.kind + "&share_tag=2" + "&mid=" + mid,
    };
  },
  makePhoneCall(evt){
    let iphone = evt.currentTarget.dataset.iphone;
    wx.makePhoneCall({
      phoneNumber: iphone
    });
  },
  setShow(){
    this.setData({show:!this.data.show});
  },
  getData() {
    let urlStr = app.getNetAddresss(
      "plugin.share-activity.frontend.activity.index"
    );
    let that = this;
    app._getNetWork({
      data: {
        activity_id: that.data.kind,
      },
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          if(res.data.no_show_back) {
            wx.hideHomeButton();
          }
          if (app._isTextEmpty(res.data.background_thumb)) {
            that.setData({
              bosPto: false,
            });
          }
          if (res.data.agreement) {
            res.data.agreement = that.replaceDetail(res.data.agreement);
          }
          that.setData({
            infoList: res.data,
            audio_link: res.data.audio_link,
            browse_count: res.data.browse_count,
            browse_member: res.data.browse_member,
            share_content: res.data.share_content,
            share_thumb: res.data.share_thumb,
            share_title: res.data.share_title,
            store_id: res.data.store_id,
            poster_open:res.data.poster_open,
            style: res.data.style
          });

          that.setDataByTabIndex();
          that.countdown();
          if (that.data.audio_link) {
            that.audioCtx = wx.createInnerAudioContext("myAudio");
            that.audioCtx.src = that.data.audio_link;
            that.audioCtx.autoplay = true;
            // that.audioPlay();
          }
          if (res.data.open_group_list == 1) {
            this.getGroupData();
          }
          that.getOrderData();
          if (res.data.award_list == 1) {
            that.getAwardData();
          }
          if (res.data.style == 1) {
            this.getBrowseList();
          }

          wx.setNavigationBarTitle({
            title: res.data.name,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  audioPlay: function () {
    this.audioCtx.play();
    this.setData({
      songStop: false,
    });
  },
  audioPause: function () {
    this.audioCtx.pause();
    this.setData({
      songStop: true,
    });
  },
  // 获取购买列表
  getOrderData() {
    let that = this;
    let json = {
      activity_id: that.data.kind,
    };
    let urlStr = app.getNetAddresss(
      "plugin.share-activity.frontend.activity.getOrders"
    );
    app._getNetWork({
      data: json,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            buy_count: res.data.buy_count,
            orders: res.data.orders,
            sales_count: res.data.sales_count
          });
          if (res.data.orders.length <= 4) {
            that.setData({
              newGmBox: false,
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 获取奖励列表
  getAwardData() {
    let that = this;
    let json = {
      activity_id: that.data.kind,
    };
    let urlStr = app.getNetAddresss(
      "plugin.share-activity.frontend.activity.getAwards"
    );
    app._getNetWork({
      data: json,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            award_count: res.data.award_count,
            awards: res.data.awards,
          });
          if (res.data.awards.length <= 4) {
            that.setData({
              lingquBox: false,
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
   // 获取拼团列表
   getGroupData() {
    if(!this.data.groupLoadMore) return;
    let json = {
      id: this.data.infoList.group_id,
      page: this.data.groupPage
    };
    let urlStr = app.getNetAddresss("plugin.share-activity.frontend.activity.all-team");
    app._getNetWork({
      data: json,
      url: urlStr,
      success: (resdata)=> {
        let res = resdata.data;
        if (res.result == 1) {
          this.data.groupPage += 1;
          this.setData({
            groupLoadMore: res.data.last_page !== res.data.current_page,
            groupData: this.data.groupData.concat(res.data.data),
            uid: wx.getStorageSync("yz_uid")
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  setGroupPop(e) {
    console.log(e)
    let status = e.currentTarget.dataset.status;
    this.setData({
      showGroupPop: status
    });
  },
  getBrowseList(more) {
    if(!this.data.browseLoadMore || this.data.browsePage > 8) return;
    let json = {
      activity_id: this.data.kind,
      page: this.data.browsePage
    };
    let urlStr = app.getNetAddresss("plugin.share-activity.frontend.activity.browse-member");
    app._getNetWork({
      data: json,
      url: urlStr,
      success: (resdata)=> {
        let res = resdata.data;
        if (res.result == 1) {
          let chunkedArray = this.chunkArray(res.data.data, 5);
          this.data.browsePage += 1;
          this.setData({
            browseLoadMore: res.data.last_page !== res.data.current_page,
            browseData: this.data.browseData.concat(chunkedArray),
            currentSwperIndex: this.activeIndex || 0
          });
          if(res.data.current_page == 1 && res.data.last_page > 1){
            this.getBrowseList();
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  chunkArray(arr, chunkSize) {
    // 拆分数组
    let result = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
      result.push(arr.slice(i, i + chunkSize));
    }
    return result;
  },
  changeSwipe(e){
    if(this.data.browseData.length == e.detail.current + 2) {
      this.activeIndex = e.detail.current;
      this.getBrowseList(true);
    }
  },
  // 加入该团按钮
  clickAdd(e) {
    this.groupDetailID = e.target.dataset.id || e.currentTarget.dataset.id;
    this.toGoods({activityType: 'GroupDetail'});
  }
});
